#import "MainViewController.h"
#import <Masonry/Masonry.h>
#import <AVFoundation/AVFoundation.h>
#import "LightSettingBarController.h"
#import "LightSettingModel.h"
#import <Photos/Photos.h>
#import <PhotosUI/PhotosUI.h>
#import "CameraPreviewView.h"
#import "MainContentView.h"
#import <sys/utsname.h>

@interface MainViewController () <AVCapturePhotoCaptureDelegate>
@property (nonatomic, strong) NSURL *livePhotoMovieURL;
@property (nonatomic, strong) NSData *jpegData;
#pragma mark - UI
@property (nonatomic, strong) MainContentView *mainContentView;

#pragma mark - 相机相关
@property (nonatomic, strong) AVCaptureSession *session;
@property (nonatomic, strong) AVCapturePhotoOutput *photoOutput;
@property (nonatomic, strong) AVCaptureDevice *cameraDevice;

#pragma mark - 业务数据
@property (nonatomic, strong) LightSettingModel *settingModel;
@property (nonatomic, strong) LightSettingBarController *lightBarVC;
@property (nonatomic, assign) BOOL isLightBarVisible;
@property (nonatomic, assign) NSInteger countdownValue;
@property (nonatomic, strong) NSTimer *countdownTimer;
@end

@implementation MainViewController

#pragma mark - 生命周期
- (void)viewDidLoad {
    [super viewDidLoad];
    // 背景色将在applyInitialSettings中设置
    [self.view addSubview:self.mainContentView];
    [self.mainContentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    [self startArrowFloatAnimation];
    [self setupCameraPreview];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    // 在viewDidAppear中进行事件绑定，确保按钮已经完全初始化
    [self setupButtonActions];
    
    // 调试信息
    NSLog(@"按钮事件绑定完成");
}

- (void)setupButtonActions {
    // 移除之前的事件绑定，避免重复绑定
    [self.mainContentView.lightSettingButton removeTarget:self action:@selector(lightSettingButtonTapped) forControlEvents:UIControlEventTouchUpInside];
    [self.mainContentView.captureButton removeTarget:self action:@selector(captureButtonTapped) forControlEvents:UIControlEventTouchUpInside];
    
    // 重新绑定事件
    [self.mainContentView.lightSettingButton addTarget:self action:@selector(lightSettingButtonTapped) forControlEvents:UIControlEventTouchUpInside];
    [self.mainContentView.captureButton addTarget:self action:@selector(captureButtonTapped) forControlEvents:UIControlEventTouchUpInside];
    
    // 确保按钮可以响应触摸事件
    self.mainContentView.lightSettingButton.userInteractionEnabled = YES;
    self.mainContentView.captureButton.userInteractionEnabled = YES;
    
    NSLog(@"按钮事件重新绑定完成");
}

#pragma mark - 懒加载控件
- (MainContentView *)mainContentView {
    if (!_mainContentView) {
        _mainContentView = [[MainContentView alloc] init];
    }
    return _mainContentView;
}

- (LightSettingBarController *)lightBarVC {
    if (!_lightBarVC) {
        _lightBarVC = [[LightSettingBarController alloc] init];
        _lightBarVC.settingModel = self.settingModel;
        _lightBarVC.modalPresentationStyle = UIModalPresentationOverCurrentContext;
        __weak typeof(self) weakSelf = self;
        _lightBarVC.onSettingChanged = ^(LightSettingModel *model) {
            [weakSelf applyLightSettings:model];
        };
    }
    return _lightBarVC;
}

- (LightSettingModel *)settingModel {
    if (!_settingModel) {
        _settingModel = [[LightSettingModel alloc] init];
    }
    return _settingModel;
}

#pragma mark - 相机初始化
- (void)setupCameraPreview {
    // 检查相机权限
    [self checkCameraPermission:^{
        [self setupCameraSession];
    }];
}

- (void)checkCameraPermission:(void(^)(void))completion {
    AVAuthorizationStatus status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    
    switch (status) {
        case AVAuthorizationStatusAuthorized:
            NSLog(@"相机权限已授权");
            if (completion) {
                completion();
            }
            break;
            
        case AVAuthorizationStatusNotDetermined:
            NSLog(@"相机权限未确定，请求权限");
            [self requestCameraPermission:completion];
            break;
            
        case AVAuthorizationStatusDenied:
            NSLog(@"相机权限被拒绝");
            [self showPermissionAlert:@"请在设置中开启相机权限"];
            break;
            
        case AVAuthorizationStatusRestricted:
            NSLog(@"相机权限受限");
            [self showPermissionAlert:@"相机权限受限，无法使用拍照功能"];
            break;
    }
}

- (void)requestCameraPermission:(void(^)(void))completion {
    [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (granted) {
                NSLog(@"相机权限已授权");
                if (completion) {
                    completion();
                }
            } else {
                NSLog(@"相机权限被拒绝");
                [self showPermissionAlert:@"相机权限被拒绝，无法使用拍照功能"];
            }
        });
    }];
}

- (void)setupCameraSession {
    self.session = [[AVCaptureSession alloc] init];
    self.session.sessionPreset = AVCaptureSessionPresetPhoto;

    // 直接指定前置摄像头
    AVCaptureDevice *frontCamera = [AVCaptureDevice defaultDeviceWithDeviceType:AVCaptureDeviceTypeBuiltInWideAngleCamera mediaType:AVMediaTypeVideo position:AVCaptureDevicePositionFront];
    if (!frontCamera) {
        NSLog(@"未找到前置摄像头");
        return;
    }
    self.cameraDevice = frontCamera;
    NSError *error = nil;
    AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:frontCamera error:&error];
    if (error) {
        NSLog(@"创建前置摄像头输入失败: %@", error);
        return;
    }
    // 移除所有旧的input，确保只用前置摄像头
    for (AVCaptureInput *oldInput in self.session.inputs) {
        [self.session removeInput:oldInput];
    }
    if ([self.session canAddInput:input]) {
        [self.session addInput:input];
    }
    
    // 配置照片输出
    self.photoOutput = [[AVCapturePhotoOutput alloc] init];
    if ([self.session canAddOutput:self.photoOutput]) {
        [self.session addOutput:self.photoOutput];
        
        // 启用Live Photo捕获
        if (@available(iOS 9.1, *)) {
            if (self.photoOutput.isLivePhotoCaptureSupported) {
                self.photoOutput.livePhotoCaptureEnabled = YES;
                NSLog(@"Live Photo捕获已启用");
            }
        }
    }
    
    [self.mainContentView.cameraPreview setupSession:self.session];
    // 启动
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [self.session startRunning];
    });
    
    // 应用初始设置
    [self applyInitialSettings];
}

- (void)applyInitialSettings {
    // 应用所有初始设置
    // 默认不应用补光蒙层，只应用屏幕亮度
    [self setScreenBrightness:self.settingModel.brightness];
    [self setAppBackgroundColor:self.settingModel.selectedColor];
    [self setCameraZoom:self.settingModel.zoomValue];
    [self.mainContentView.cameraPreview setZoom:self.settingModel.zoomValue];
    [self.mainContentView.cameraPreview setMirrored:self.settingModel.mirrorEnabled];
}

- (void)setCameraZoom:(CGFloat)zoom {
    if (!self.cameraDevice) {
        NSLog(@"相机设备未初始化");
        return;
    }
    
    // 确保缩放值在有效范围内
    CGFloat minZoom = self.cameraDevice.minAvailableVideoZoomFactor;
    CGFloat maxZoom = self.cameraDevice.maxAvailableVideoZoomFactor;
    CGFloat clampedZoom = MAX(minZoom, MIN(maxZoom, zoom));
    
    NSLog(@"相机设备缩放范围: %.1fx - %.1fx, 设置值: %.1fx", minZoom, maxZoom, clampedZoom);
    
    NSError *error = nil;
    [self.cameraDevice lockForConfiguration:&error];
    if (error) {
        NSLog(@"锁定相机配置失败: %@", error);
        return;
    }
    
    // 设置相机缩放
    self.cameraDevice.videoZoomFactor = clampedZoom;
    
    [self.cameraDevice unlockForConfiguration];
    
    NSLog(@"相机缩放设置为: %.1fx", clampedZoom);
    NSLog(@"当前相机缩放因子: %.1fx", self.cameraDevice.videoZoomFactor);
}

- (void)setScreenBrightness:(NSInteger)brightness {
    // 将百分比转换为0.0-1.0的范围
    CGFloat brightnessValue = brightness / 100.0;
    
    // 设置屏幕亮度
    [UIScreen mainScreen].brightness = brightnessValue;
    
    NSLog(@"屏幕亮度设置为: %ld%% (%.2f)", (long)brightness, brightnessValue);
}

- (void)setAppBackgroundColor:(UIColor *)color {
    // 改变应用界面的背景色
    self.view.backgroundColor = color;
    
    NSLog(@"应用界面背景色设置为: %@", color);
}

- (void)showPermissionAlert:(NSString *)message {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"权限提示" message:message preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *settingsAction = [UIAlertAction actionWithTitle:@"去设置" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString] options:@{} completionHandler:nil];
    }];
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    
    [alert addAction:settingsAction];
    [alert addAction:cancelAction];
    
    [self presentViewController:alert animated:YES completion:nil];
}

#pragma mark - 补光设置Bar弹出/收起
- (void)lightSettingButtonTapped {
    NSLog(@"lightSettingButtonTapped called");
    
    if (self.isLightBarVisible) {
        [self hideLightBar];
    } else {
        [self showLightBar];
    }
}

- (void)showLightBar {
    LightSettingBarController *barVC = [[LightSettingBarController alloc] init];
    barVC.settingModel = self.settingModel;
    barVC.modalPresentationStyle = UIModalPresentationOverCurrentContext;
    __weak typeof(self) weakSelf = self;
    barVC.onSettingChanged = ^(LightSettingModel *model) {
        [weakSelf applyLightSettings:model];
    };
    barVC.onRequestHide = ^{
        [weakSelf hideLightBar];
    };
    [self addChildViewController:barVC];
    barVC.view.frame = self.view.bounds;
    barVC.view.alpha = 0;
    [self.view addSubview:barVC.view];
    [barVC didMoveToParentViewController:self];
    barVC.view.transform = CGAffineTransformMakeTranslation(0, barVC.view.bounds.size.height);
    [UIView animateWithDuration:0.3 animations:^{
        barVC.view.alpha = 1;
        barVC.view.transform = CGAffineTransformIdentity;
    }];
    self.lightBarVC = barVC;
    self.isLightBarVisible = YES;
}

- (void)hideLightBar {
    [UIView animateWithDuration:0.3 animations:^{
        self.lightBarVC.view.alpha = 0;
        self.lightBarVC.view.transform = CGAffineTransformMakeTranslation(0, self.lightBarVC.view.bounds.size.height);
    } completion:^(BOOL finished) {
        [self.lightBarVC.view removeFromSuperview];
        [self.lightBarVC removeFromParentViewController];
        self.lightBarVC = nil;
    }];
    self.isLightBarVisible = NO;
}

#pragma mark - 动画
- (void)startArrowFloatAnimation {
    __weak typeof(self) weakSelf = self;
    
    // 使用更安全的动画方式，确保不影响触摸事件
    [UIView animateWithDuration:1.0 
                          delay:0 
         usingSpringWithDamping:0.8 
          initialSpringVelocity:0.2 
                        options:UIViewAnimationOptionAutoreverse | UIViewAnimationOptionRepeat | UIViewAnimationOptionAllowUserInteraction
                     animations:^{
        weakSelf.mainContentView.lightSettingButton.transform = CGAffineTransformMakeTranslation(0, -8);
    } completion:nil];
}

- (void)stopArrowFloatAnimation {
    [self.mainContentView.lightSettingButton.layer removeAllAnimations];
    self.mainContentView.lightSettingButton.transform = CGAffineTransformIdentity;
}



#pragma mark - 拍照与倒计时
- (void)captureButtonTapped {
    NSInteger timerType = self.settingModel.timerType;
    if (timerType == 1) {
        [self startCountdown:3];
    } else if (timerType == 2) {
        [self startCountdown:7];
    } else {
        [self takePhoto];
    }
}

- (void)startCountdown:(NSInteger)seconds {
    self.countdownValue = seconds;
    [self.mainContentView.cameraPreview showCountdown:self.countdownValue];
    [self.countdownTimer invalidate];
    self.countdownTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(countdownTick) userInfo:nil repeats:YES];
}

- (void)countdownTick {
    self.countdownValue--;
    if (self.countdownValue > 0) {
        [self.mainContentView.cameraPreview showCountdown:self.countdownValue];
    } else {
        [self.countdownTimer invalidate];
        [self.mainContentView.cameraPreview hideCountdown];
        [self takePhoto];
    }
}

- (void)takePhoto {
    AVCapturePhotoSettings *settings = [AVCapturePhotoSettings photoSettings];
    
    // 如果LIVE开启，设置Live Photo格式
    if (self.settingModel.liveEnabled) {
        // 创建临时MOV文件路径
        self.livePhotoMovieURL = [self temporaryMovieURL];
        settings.livePhotoMovieFileURL = self.livePhotoMovieURL;
        
        NSLog(@"设置Live Photo格式，视频文件URL: %@", settings.livePhotoMovieFileURL);
    }
    
    // 确保拍照时使用当前的缩放设置
    NSLog(@"拍照时相机缩放因子: %.1fx", self.cameraDevice.videoZoomFactor);
    
    [self.photoOutput capturePhotoWithSettings:settings delegate:self];
}



- (NSURL *)temporaryMovieURL {
    NSString *tempDir = NSTemporaryDirectory();
    NSString *filePath = [tempDir stringByAppendingPathComponent:
                         [NSString stringWithFormat:@"%@.mov", [[NSUUID UUID] UUIDString]]];
    return [NSURL fileURLWithPath:filePath];
}

- (void)saveLivePhotoToPhotoLibrary {
    // 创建临时文件路径
    NSString *tempDir = NSTemporaryDirectory();
    NSString *uuid = [[NSUUID UUID] UUIDString];
    NSURL *jpgURL = [NSURL fileURLWithPath:[tempDir stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.jpg", uuid]]];
    NSURL *movURL = [NSURL fileURLWithPath:[tempDir stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.mov", uuid]]];
    
    NSError *error;
    // 写入JPEG文件
    [self.jpegData writeToURL:jpgURL options:NSDataWritingAtomic error:&error];
    if (error) {
        NSLog(@"写入JPEG失败: %@", error.localizedDescription);
        return;
    }
    
    // 移动视频文件（系统生成的临时文件）
    [[NSFileManager defaultManager] moveItemAtURL:self.livePhotoMovieURL toURL:movURL error:&error];
    if (error) {
        NSLog(@"移动视频文件失败: %@", error.localizedDescription);
        return;
    }
    
    // 检查相册权限
    [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
        if (status != PHAuthorizationStatusAuthorized) {
            NSLog(@"无相册访问权限");
            return;
        }
        
        // 保存到相册
        [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
            PHAssetCreationRequest *request = [PHAssetCreationRequest creationRequestForAsset];
            
            // 添加图片资源
            [request addResourceWithType:PHAssetResourceTypePhoto 
                                fileURL:jpgURL 
                                options:nil];
            
            // 添加配对视频资源
            [request addResourceWithType:PHAssetResourceTypePairedVideo 
                                fileURL:movURL 
                                options:nil];
            
        } completionHandler:^(BOOL success, NSError * _Nullable error) {
            // 清理临时文件
            [[NSFileManager defaultManager] removeItemAtURL:jpgURL error:nil];
            [[NSFileManager defaultManager] removeItemAtURL:movURL error:nil];
            
            if (success) {
                NSLog(@"Live Photo保存成功!");
            } else {
                NSLog(@"保存失败: %@", error.localizedDescription);
            }
        }];
    }];
}





#pragma mark - 拍照回调与结果
- (void)showResult:(BOOL)success {
    [self.mainContentView.cameraPreview showResult:success];
}

- (void)applyLightSettings:(LightSettingModel *)model {
    // 根据按钮tag来决定应用哪个设置
    switch (model.currentSettingType) {
        case ButtonTagLive:
            // LIVE功能不需要实时应用，只在拍照时使用
            break;
        case ButtonTagMirror:
            [self.mainContentView.cameraPreview setMirrored:model.mirrorEnabled];
            break;
        case ButtonTagTimerOff:
        case ButtonTagTimer3s:
        case ButtonTagTimer7s:
            // 定时功能不需要实时应用，只在拍照时使用
            break;
        case ButtonTagZoom:
            // 放大功能单独处理，设置相机设备缩放和预览层变换
            [self setCameraZoom:model.zoomValue];
            [self.mainContentView.cameraPreview setZoom:model.zoomValue];
            break;
        case ButtonTagBrightness:
            // 亮度功能单独处理，调节屏幕亮度
            [self setScreenBrightness:model.brightness];
            break;
        case ButtonTagColor:
            // 颜色选择功能，改变应用界面背景色
            [self setAppBackgroundColor:model.selectedColor];
            break;
        case ButtonTagDefault:
        default:
            // 默认情况只应用镜像设置
            [self.mainContentView.cameraPreview setMirrored:model.mirrorEnabled];
            break;
    }
}

- (void)playLiveFlashEffect {
    [self.mainContentView.cameraPreview playLiveFlashEffect];
}

#pragma mark - AVCapturePhotoCaptureDelegate
- (void)captureOutput:(AVCapturePhotoOutput *)output didFinishProcessingPhoto:(AVCapturePhoto *)photo error:(NSError *)error {
    if (error) {
        NSLog(@"照片处理失败: %@", error);
        [self showResult:NO];
        return;
    }
    
    // 获取JPEG数据
    self.jpegData = [photo fileDataRepresentation];
    
    if (self.jpegData) {
        NSLog(@"照片处理完成，Live Photo状态: %@", self.settingModel.liveEnabled ? @"开启" : @"关闭");
        
        if (!self.settingModel.liveEnabled) {
            // 普通照片模式，直接保存
            NSLog(@"普通照片模式，直接保存");
            UIImage *image = [UIImage imageWithData:self.jpegData];
            if (self.settingModel.mirrorEnabled) {
                image = [self mirroredImage:image];
            }
            [self saveImageToAlbum:image];
            [self showResult:YES];
        }
    } else {
        NSLog(@"照片数据为空");
        [self showResult:NO];
    }
}

- (void)captureOutput:(AVCapturePhotoOutput *)output 
didFinishRecordingLivePhotoMovieForEventualFileAtURL:(NSURL *)outputFileURL 
      resolvedSettings:(AVCaptureResolvedPhotoSettings *)resolvedSettings {
    // Live Photo视频已录制完成
    NSLog(@"Live Photo视频录制完成: %@", outputFileURL);
    self.livePhotoMovieURL = outputFileURL;
}

- (void)captureOutput:(AVCapturePhotoOutput *)output 
didFinishProcessingLivePhotoToMovieFileAtURL:(NSURL *)outputFileURL 
             duration:(CMTime)duration 
      photoDisplayTime:(CMTime)photoDisplayTime 
      resolvedSettings:(AVCaptureResolvedPhotoSettings *)resolvedSettings 
                error:(NSError *)error {
    if (error) {
        NSLog(@"Live Photo视频处理失败: %@", error);
        self.livePhotoMovieURL = nil;
    } else {
        NSLog(@"Live Photo视频处理成功: %@", outputFileURL);
        self.livePhotoMovieURL = outputFileURL;
    }
}

- (void)captureOutput:(AVCapturePhotoOutput *)output 
didFinishCaptureForResolvedSettings:(AVCaptureResolvedPhotoSettings *)resolvedSettings 
                error:(NSError *)error {
    if (error) {
        NSLog(@"捕获过程失败: %@", error.localizedDescription);
        [self showResult:NO];
        return;
    }
    
    // 如果是Live Photo模式，确保有有效数据
    if (self.settingModel.liveEnabled) {
        if (!self.jpegData || !self.livePhotoMovieURL) {
            NSLog(@"缺少照片或视频数据，保存为普通照片");
            if (self.jpegData) {
                UIImage *image = [UIImage imageWithData:self.jpegData];
                if (self.settingModel.mirrorEnabled) {
                    image = [self mirroredImage:image];
                }
                [self saveImageToAlbum:image];
            }
            [self showResult:YES];
            return;
        }
        
        // 保存Live Photo到相册
        [self saveLivePhotoToPhotoLibrary];
    }
    
    [self showResult:YES];
}

- (void)saveImageToAlbum:(UIImage *)image {
    [self checkPhotoLibraryPermission:^{
        [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
            [PHAssetChangeRequest creationRequestForAssetFromImage:image];
        } completionHandler:^(BOOL success, NSError * _Nullable error) {
            if (!success) {
                NSLog(@"保存照片失败: %@", error);
            }
        }];
    }];
}

- (void)checkPhotoLibraryPermission:(void(^)(void))completion {
    PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
    
    switch (status) {
        case PHAuthorizationStatusAuthorized:
        case PHAuthorizationStatusLimited:
            NSLog(@"相册权限已授权");
            if (completion) {
                completion();
            }
            break;
            
        case PHAuthorizationStatusNotDetermined:{
            NSLog(@"相册权限未确定，请求权限");
            [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    if (status == PHAuthorizationStatusAuthorized || status == PHAuthorizationStatusLimited) {
                        NSLog(@"相册权限已授权");
                        if (completion) {
                            completion();
                        }
                    } else {
                        NSLog(@"相册权限被拒绝");
                        [self showPermissionAlert:@"相册权限被拒绝，无法保存照片"];
                    }
                });
            }];
        }
            break;
        case PHAuthorizationStatusDenied:{
            NSLog(@"相册权限被拒绝");
            [self showPermissionAlert:@"请在设置中开启相册权限"];
        }
            break;
            
        case PHAuthorizationStatusRestricted:{
            NSLog(@"相册权限受限");
            [self showPermissionAlert:@"相册权限受限，无法保存照片"];
        }
            break;
    }
}



- (UIImage *)mirroredImage:(UIImage *)image {
    return [UIImage imageWithCGImage:image.CGImage scale:image.scale orientation:UIImageOrientationLeftMirrored];
}

@end 
